//
//  BlueToothManager.swift
//  HSMainViewControllerHandler
//
//  Created by haisheng huang on 16/4/20.
//  Copyright © 2016年 haisheng huang. All rights reserved.
//

import Foundation
import CoreBluetooth

@available(iOS 7.0, *)
class BlueToothManager: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate, CBPeripheralManagerDelegate {

    struct Static {
        static var onceToken: Int = 0
        static var instance: BlueToothManager? = nil
    }

    private static var __once: () = {
            Static.instance = BlueToothManager()
        }()

    
    /**
     * BlueToothManager Delegate
     **/
    weak var delegate: BlueToothManagerDelegate?
    
    /**
     * CBCentralManager
     **/
    var h_centralManager:CBCentralManager?;
    
    /**
     * CBPeripheral
     **/
    var h_peripheral: CBPeripheralManager?
    
    
    /**
     *  BlueToothManager 的单例
     **/
    class var sharedInstance: BlueToothManager {
    
        _ = BlueToothManager.__once
        
        return Static.instance!
    }
    
    /**
     *  便利构造初始化
     *
     **/
    convenience init(delegate: BlueToothManagerDelegate?) {
    
        self.init()
        
        self.delegate = delegate
        self.h_centralManager = CBCentralManager.init(delegate: self, queue: nil, options: [CBCentralManagerOptionShowPowerAlertKey  : true])
        self.h_peripheral = CBPeripheralManager.init(delegate: self, queue: nil)
        
        
    }
    
    // MARK: CBCentralManagerDelegate
    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        
        //检测中心设备蓝牙的状态变化
//        print("centralManagerDidUpdateState: \(central.state)")
    }
    
    func centralManager(_ central: CBCentralManager, willRestoreState dict: [String : Any]) {
        //当app进入后台模式时调用，可以实现保护和恢复的一些操作
//        print("willRestoreState")
    }
    
    func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
        //中心设备已经建立与外设的蓝牙连接
//        print("didConnectPeripheral")
    }
    
    func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
        //中心设备已经断开外设的蓝牙连接
//        print("didDisconnectPeripheral")
    }
    
    func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
        //中心设备与外设的蓝牙连接失败
//        print("didFailToConnectPeripheral")
    }
    
    func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
        //中心设备已经发现外设
//        print("didDiscoverPeripheral")
    }
    
    // MARK: CBPeripheralManagerDelegate
    func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) {
        //这个方法是必须实现的 状态可用后可以发送广播
//        print("peripheralManagerDidUpdateState")
        
    }
    
    func peripheralManagerDidStartAdvertising(_ peripheral: CBPeripheralManager, error: Error?) {
        //开始发送广播时调用的方法
//        print("peripheralManagerDidStartAdvertising")
        
    }
    
    func peripheralManagerIsReady(toUpdateSubscribers peripheral: CBPeripheralManager) {
        //外设准备更新特征值时调用的方法
//        print("peripheralManagerIsReadyToUpdateSubscribers")
    }
    
    func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveRead request: CBATTRequest) {
        //收到读请求时触发的方法
//        print("didReceiveReadRequest")
    }
    
    func peripheralManager(_ peripheral: CBPeripheralManager, willRestoreState dict: [String : Any]) {
        //连接回复时调用的方法 和centralManager类似
//        print("willRestoreState")
    }
    
    func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveWrite requests: [CBATTRequest]) {
        //收到写请求时触发的方法
//        print("didReceiveWriteRequests")
    }
    
    func peripheralManager(_ peripheral: CBPeripheralManager, didAdd service: CBService, error: Error?) {
        //添加服务调用的回调
//        print("didAddService")
    }
    
    func peripheralManager(_ peripheral: CBPeripheralManager, central: CBCentral, didSubscribeTo characteristic: CBCharacteristic) {
        //当一个central设备订阅一个特征值时调用的方法
//        print("didSubscribeToCharacteristic")
    }
    
    func peripheralManager(_ peripheral: CBPeripheralManager, central: CBCentral, didUnsubscribeFrom characteristic: CBCharacteristic) {
        //取消订阅一个特征值时调用的方法
//        print("didUnsubscribeFromCharacteristic")
    }
    
    // MARK: CBPeripheralDelegate
    func peripheralDidUpdateName(_ peripheral: CBPeripheral) {
        //外设已经更新了命名
//        print("peripheralDidUpdateName")
    }
    
    func peripheralDidUpdateRSSI(_ peripheral: CBPeripheral, error: Error?) {
        //Use {@link peripheral:didReadRSSI:error:} instead deprecated ios8.0
        //This method returns the result of a @link readRSSI: @/link call
        
//        print("peripheralDidUpdateRSSI")
    }
    
    func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
        //外设发现中心设备的服务
//        print("didDiscoverServices")
    }
    
    func peripheral(_ peripheral: CBPeripheral, didModifyServices invalidatedServices: [CBService]) {
        //外设变更了服务连接
//        print("didModifyServices")
    }
    
    func peripheral(_ peripheral: CBPeripheral, didReadRSSI RSSI: NSNumber, error: Error?) {
        //外设读取RSSI(信号强度)
//        print("didReadRSSI")
    }
    
    func peripheral(_ peripheral: CBPeripheral, didWriteValueFor descriptor: CBDescriptor, error: Error?) {
        //写描述信息时触发的方法
//        print("didWriteValueForDescriptor")
    }
    
    func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor descriptor: CBDescriptor, error: Error?) {
        //特征的描述值更新时触发的方法
//        print("didUpdateValueForDescriptor")
    }
    
    func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
        //发现特征值的描述信息触发的方法
//        print("didDiscoverCharacteristicsForService")
    }
    
    func peripheral(_ peripheral: CBPeripheral, didDiscoverIncludedServicesFor service: CBService, error: Error?) {
        //在服务中发现子服务回调的方法
//        print("didDiscoverIncludedServicesForService")
    }
    
    func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {
        //向特征值写数据时回调的方法
//        print("didWriteValueForCharacteristic")
    }
    
    func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
        //特征值更新时回调的方法
//        print("didUpdateValueForCharacteristic")
    }
    
    func peripheral(_ peripheral: CBPeripheral, didDiscoverDescriptorsFor characteristic: CBCharacteristic, error: Error?) {
        //发现特征值的描述信息触发的方法
//        print("didDiscoverDescriptorsForCharacteristic")
    }
    
    func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) {
        //特征值的通知设置改变时触发的方法
//        print("didUpdateNotificationStateForCharacteristic")
    }
    
}

@available(iOS 7.0, *)
@objc protocol BlueToothManagerDelegate: NSObjectProtocol {

    @objc optional func sayHello()
    
}

